package com.jiyi.widget.picshow;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.jiyi.widget.picshow.PhotoViewAttacher.OnPhotoTapListener;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.utils.DeviceUtil;

import java.io.File;

public class ImageDetailFragment extends Fragment {
	private String mImageUrl;
	private ImageView mImageView;
	private ProgressBar progressBar;
	private PhotoViewAttacher mAttacher;
	private PopupWindow mPopupWindow;
	final int SAVE_PIC = 1;

	public static ImageDetailFragment newInstance(String imageUrl) {
		final ImageDetailFragment f = new ImageDetailFragment();

		final Bundle args = new Bundle();
		args.putString("url", imageUrl);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initPop();
		mImageUrl = getArguments() != null ? getArguments().getString("url")
				: null;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View v = inflater.inflate(R.layout.image_detail_fragment,
				container, false);
		mImageView = (ImageView) v.findViewById(R.id.image);
		mAttacher = new PhotoViewAttacher(mImageView);
		mAttacher.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View view) {
				if (!mPopupWindow.isShowing()) {
					mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
				}
				return false;
			}
		});
		mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {

			@Override
			public void onPhotoTap(View arg0,float x,float y, float arg1, float arg2) {
				getActivity().finish();
			}
		});
		progressBar = (ProgressBar) v.findViewById(R.id.loading);
		return v;
	}

	void initPop() {
		View tip = getActivity().getLayoutInflater().inflate(
				R.layout.pop_pic_handle, null);
		// TextView tvToFriend = (TextView) tip.findViewById(R.id.tvToFriend);
		TextView tvSavePic = (TextView) tip.findViewById(R.id.tvSavePic);
		TextView tvCancle = (TextView) tip.findViewById(R.id.tvCancle);
		// tvToFriend.setText("发送微信朋友");
		tvSavePic.setText("保存图片");
		tvCancle.setText("取消");
		// tvToFriend.setOnClickListener(toFriendClickListener);
		tvSavePic.setOnClickListener(savePicClickListener);
		tvCancle.setOnClickListener(noClickListener);

		mPopupWindow = new PopupWindow(tip, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		mPopupWindow.setAnimationStyle(R.style.FromToTop);
		mPopupWindow.setBackgroundDrawable(new ColorDrawable());
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setTouchable(true);
		mPopupWindow.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					hidePop();
					return true;
				}
				return false;
			}
		});
	}

	OnClickListener toFriendClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			// hidePop();
		}
	};

	OnClickListener savePicClickListener = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			checkPermission();
		}
	};

	OnClickListener noClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			hidePop();
		}
	};

	void hidePop() {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		 Glide.with(getActivity()).load(mImageUrl)
//		 .error(AppConfig.PIC_PALACE).into(mImageView);
		Glide.with(getContext()).load(mImageUrl).override(DeviceUtil.getInstance().getScreenWidth()/2,DeviceUtil.getInstance().getScreenHeight()/2)
				.placeholder(AppConfig.PIC_PALACE)
				.into(new GlideDrawableImageViewTarget(mImageView) {

					@Override
					public void onLoadStarted(Drawable placeholder) {
						// 开始加载图片
						progressBar.setVisibility(View.VISIBLE);
					}

					@Override
					public void onLoadFailed(Exception e, Drawable errorDrawable) {
						progressBar.setVisibility(View.GONE);

					}

					@Override
					public void onResourceReady(GlideDrawable resource,
							GlideAnimation<? super GlideDrawable> glideAnimation) {
						super.onResourceReady(resource, glideAnimation);
						mImageView.setImageDrawable(resource);
						progressBar.setVisibility(View.GONE);
						mAttacher.update();
					}
				});
	}

	Handler mHandler = new Handler() {

		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case SAVE_PIC:
				if (!getActivity().isFinishing()) {
					hidePop();
					Toast.makeText(getActivity(), "保存到系统相册", Toast.LENGTH_SHORT)
							.show();
				}
				break;

			default:
				break;
			}

		};
	};

	public void checkPermission() {

		if (PermissionUtil.checkPermission(this,PermissionUtil.WRITE))
		{
			saveImg();
		}
	}



	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == PermissionUtil.WRITE)
		{
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
			{
				saveImg();
			}
			else
			{
				ToastUtil.getInstances().showMsg("你没有保存图片的权限");
			}
		}

	}

	void saveImg()
	{
		new Thread(new Runnable() {

			@Override
			public void run() {
				Bitmap mBitmap ;
				if (mImageView.getDrawable() instanceof GlideBitmapDrawable)
				{
					mBitmap = (((GlideBitmapDrawable) mImageView.getDrawable()).getBitmap());
				}
				else
				{
					mBitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
				}

				String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), mBitmap, "title", "description");
				Uri fileUri ;
				if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
				{
					MediaScannerConnection.scanFile(getContext(), new String[]{path}, null, null);
				}
				else
				{
					fileUri = Uri.fromFile(new File(path));
					getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
				}


				mHandler.sendEmptyMessage(SAVE_PIC);
			}
		}).start();
	}
}
